import React, { createContext, ReactNode, useContext, useState } from "react";

type Todo = {
    id: number,
    text: string,
    isCompleted: boolean
}

type TodoContextType = {
    todos: Todo[];
    addTodo: (text: string) => void;
    deleteTodo: (id: number) => void;
    toggleTodo: (id: number) => void;
    editTodo: (id: number, newText: string) => void;
}

const TodoContext = createContext<TodoContextType | undefined>(undefined);

export const TodoProvider = ({ children }: { children: ReactNode }) => {
    const data = [
        {
            "id": 1,
            "text": "Shopping",
            "isCompleted": false
        },
        {
            "id": 2,
            "text": "Cooking",
            "isCompleted": true
        },
        {
            "id": 3,
            "text": "Coding",
            "isCompleted": false
        }
    ]

    const [todos, setTodos] = useState<Todo[]>(data);

    const addTodo = (text: string) => {
        if (text.trim()) {
            setTodos(prev => [...prev, { id: Date.now(), text, isCompleted: false }]);
        }
    }

    const deleteTodo = (id: number) => {
        setTodos(prev => prev.filter(todo => todo.id !== id));
    }

    const toggleTodo = (id: number) => {
        setTodos(prev =>
            prev.map(todo =>
                todo.id === id ? { ...todo, isCompleted: !todo.isCompleted } : todo
            )
        );
    }

    const editTodo = (id: number, newText: string) => {
        setTodos(prev =>
            prev.map(todo =>
                todo.id === id ? { ...todo, text: newText } : todo
            )
        );
    }

    return (
        <TodoContext.Provider value={{ todos, addTodo, deleteTodo, toggleTodo, editTodo }}>
            {children}
        </TodoContext.Provider>
    )
}

export const useTodos = (): TodoContextType => {
    const context = useContext(TodoContext);
    if (!context) {
        throw new Error("useTodos must be used with in a TodoProvider");
    }
    return context;
}